<template>
  <div class="equipmentDataManagement mt16">
    <div class="search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.Entity') }}</p>
            <div class="ipt">
              <Select v-model="searchParams.companyId"
                      @on-change="changeCompany"
                      clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="item of tagList"
                        :value="item.id" :key="item.id" :label="item.name">
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.Warehouse') }}</p>
            <div class="ipt">
              <Select v-model="searchParams.backupConfigId" clearable
                      :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item,index) of warehouseList" :value="item.id" :key="index" :label="item.backupName">
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.ApprovalStatus') }}</p>
            <div class="ipt">
              <Select clearable
                      @on-change="handleApprol"
                      v-model="searchParams.status"
                      :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="item of scrapStatusList"
                        :value="item.id"
                        :label="item.name"
                        :key="item.id"/>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.Appliedby') }}</p>
            <div class="ipt">
              <Select
                v-model="searchParams.applyBy"
                filterable
                clearable
                :placeholder="`${$t('common.selectInfo')}`"
                :remote-method="getApplicationOAList"
              >
                <Option v-for="item of OAList"
                        :value="item.id"
                        :label="item.showName"
                        :key="item.showName"/>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.ApprovalTime') }}</p>
            <div class="ipt">
              <DatePicker
                v-model="applyTimeList"
                type="datetimerange"
                format="yyyy-MM-dd HH:mm:ss"
                placement="bottom-end"
                :placeholder="`${$t('common.selectInfo')}`"
                @on-change="handleRangeChange"
              />
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn"
                      v-has="'scrapapprovalSearch'"
                      type="primary" @click="changeNum()">{{ $t('common.Query') }}</Button>
              <Button  v-has="'scrapapprovalSearch'"
                class="reset-btn"
                @click="reset()"
              >{{ $t('common.reset') }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>

    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button   v-has="'scrapapprovalExport'" @click="handleOutDel">{{ $t('common.batchExport') }}</Button>
          <Button @click="getTableColumns(columns)">
              {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
          </Button>
      </div>

      <div class="tableContent">
        <Table
          ellipsis
          ref="selection"
          @on-selection-change="onSelectChange"
          :data="dataArr"
          class="resizable-table"
          border
          @on-column-width-resize="onColumnWidthResize"
          :columns="columnsList"
        >

          <template slot-scope="{ row }" slot="approvalStatus">
            <span>{{ row.applyStatusStr }}</span>
          </template>

          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn"  v-has="'scrapapprovalCheck'"  @click="goScrapp('check',row)">
              <i class="iconfont zy-common-chakan"></i>
              <span>{{ $t('common.Check') }}</span>
            </span>

            <template v-if="ifFinish === 0 && row.applyStatus === 3">
               <span class="operationBtn"
                     v-has="'scrapapprovalApproval'"
                     @click="goScrapp('detail',row)">
              <i class="iconfont zy-common-chenggong1"></i>
              <span>{{ $t('common.Approval') }}</span>
            </span>
            </template>
          </template>
        </Table>
      </div>

      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="selectList.length"/>
        <Page placement="top" :total="total" :page-size="pageSize" :page-size-opts="pageSizeOption" :current="pageNum"
              @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
      </div>
    </div>


    <Modal :mask-closable="false"
      v-model="toggleShow"
      :title="`${$t('common.Approval')}`"
      class="modal-content-layout"
    >
      <div>
        <Form
          :show-message="false"
          label-position="top"
        >
          <FormItem>
            <template #label>
              <span style="color: red">*</span>
              <span>{{ $t('equipmentscrapped.Result') }}</span>
            </template>
            <RadioGroup v-model="form.result">
              <Radio :label=4>通过</Radio>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <Radio :label=5>不通过</Radio>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <Radio :label=6>退回</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem>
            <template #label>
              <span style="color: red">*</span>
              <span>{{ $t('equipmentscrapped.Comments') }}</span>
            </template>
            <Input type="textarea" v-model="form.scrapApprovalMessage"
                   :placeholder="`${$t('common.inputInfo')}`"/>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="default" @click="toggleShow = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="submitHandle">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>

  </div>
</template>

<script>
import fileDownload from 'js-file-download'
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "picking",
  components: {},
  props: ['ifFinish'],
  mixins:[toggleTableOperation],
  data() {
    return {
        customCacheKey:"scrapapprovaltab1",
      form: {},
      toggleShow: false,
      applyTimeList: [],
      manageByList: [],
      formInfo: {},
      selectList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      searchParams: {},
      pageSizeOption: [10, 20, 30, 40],
      warehouseList: [],
      tagList: [{id: '', name: '全部'}],
      scrapStatusList: [],
      approvalList: [
        {id: 1, name: '已提交'},
        {id: 2, name: '撤回'},
        {id: 3, name: '待审批'},
        {id: 4, name: '审批通过'},
        {id: 5, name: '审批不通过'},
        {id: 6, name: '退回'},
        {id: 7, name: '被退回'}
      ],
      columns: [
        {type: 'selection', width: 60, align: 'center'},
        // {
        //   title: '是否需要审批',
        //   key: 'applyFlag',
        //   align: "center",
        //   minWidth: 120
        // },
        {
          //title: `${ this.$t('equipmentscrapped.ApplyTime') }`,
          title: `${this.$t('equipmentscrapped.ApplyTime')}`,
          key: 'applyTime',
          align: "center",
          minWidth: 180,
            resizable: true
        },
        {
          title: `${this.$t('equipmentscrapped.ID')}`,
          key: 'backupScrapApplyNo',
          align: "center",
          minWidth: 160,
            resizable: true
        },
        {
          // title: '审批状态',
          title: `${this.$t('common.ApprovalStatus')}`,
          slot: "approvalStatus",
          key: 'applyStatusStr',
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          //title: `${this.$t('spareParts.company')}`,
          title: `${this.$t('common.company')}`,
          key: 'companyName',
          align: "center",
          minWidth: 160,
            resizable: true
        },
        {
          //title: '仓库名称',
          title: `${this.$t('common.Warehouse')}`,
          key: 'warehouseName',
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          // title: `${this.$t('common.ApplicationQuantit')}`,
          title: `${this.$t('common.ApplicationQuantit')}`,
          key: 'applyCount',
          align: "center",
          minWidth: 140,
            resizable: true
        },
        {
          // title: `${ this.$t('equipmentscrapped.ApplyBy') }`,
          title: `${this.$t('common.Appliedby')}`,
          key: 'applyBy',
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          //title: '审批时间',
          title: `${this.$t('equipmentscrapped.ApprovedTime')}`,
          key: 'approvalTime',
          align: "center",
          minWidth: 180,
            resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          minWidth: 240,
          align: "center",
          fixed: 'right'
        }
      ],
      assetsList: [],
      dataArr: [],
      OAList: [],
      timerId: null,
      userRoleName: {},
      tarGetRow: {},
    }
  },
  created() {

    if (this.ifFinish === 1) {
        this.customCacheKey = "scrapapprovaltab1"
      this.scrapStatusList = [
        {id: 4, name: '审批通过'},
        {id: 5, name: '审批不通过'},
        {id: 6, name: '已退回'},
      ]
    }
    if (this.ifFinish === 0) {
        this.customCacheKey = "scrapapprovaltab0"
      this.scrapStatusList = [{id: 3, name: '待审批'}]
    }

    this.getTableColumnsWidth(this.columns)

    this.getCompanyList()
    this.searchList()
  },
  mounted() {
    this.userRoleName = window.localStorage.getItem('ziyunFactoryUserRoleName')
  },
  methods: {
    reset(){
            this.searchParams = {};
            this.applyTimeList = []
            this.searchList()
        },
    submitHandle() {
      const params = this.form;
      const {result, rollbackRole, scrapApprovalMessage} = params;
      if (!result) {
        this.$Message.error('请选择审批结果！')
        return;
      }
      if (!scrapApprovalMessage) {
        this.$Message.error('请输入审批意见！')
        return;
      }
      params.backupScrapApprovalId = this.tarGetRow.id
      params.backupScrapApplyId = this.tarGetRow.applyId
      params.approvalRole = localStorage.getItem('ziyunFactoryUserRoleId')

      this.axios({
        method: 'post',
        url: '/dms/backup/scrapApply/doApproval',
        data: params
      }).then(res => {
        if (res.code === 200) {
          this.searchList()
          this.toggleShow = false
        } else {
          this.$Message.error(res.msg)
        }
      })
    },
    handleApprol(val) {
      // if(val){
      //  this.searchParams.approvalStatusName = this.approvalList.find(item=>item.id === val).name
      // }
      console.log(val)
      console.log(this.searchParams.approvalStatusName)
    },
    goScrapp(str, row) {
      this.tarGetRow = row
      let query = {
        status: str,
        id: ''
      }
      if (row) {
        query.companyId = row.companyId
        // query.id = row.id
        query.id = row.applyId
        query.applyStatus = row.approvalFlowSort
        // if (row.dmsBackupScrapApplyDetails && row.dmsBackupScrapApplyDetails.length){
        //   row.dmsBackupScrapApplyDetails.forEach(val=>{
        //     val.companyName = row.companyName
        //     val.backupName = row.backupName + '仓库'
        //     val.approvalByName = row.approvalByName
        //     val.approvalStatus = row.approvalStatus
        //     val.remarkInfo = row.remark
        //   })
        // }
        // localStorage.setItem('scarpList',JSON.stringify(row.dmsBackupScrapApplyDetails))
      }
      if (str === 'check' || str === 'edit') {
        this.$router.push({
          path: '/spareParts/operations/scrapapprovalModule',
          query
        })
      }
      if (str === 'detail') {
        this.toggleShow = true
      }
    },
    getmanageByList(query) {
      if (query !== '') {
        this.loading = true
        this.axios({
          method: 'post',
          url: '/dms/dmsBackupConfig/queryBackupsManageBy',
          data: {
            manageByName: query
          }
        }).then(res => {
          if (res.code === 200) {
            this.manageByList = res.data.map(item => {
              return {
                ...item,
                showName: item.manageByName + '--' + item.backupName
              }
            })
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.manageByList = []
      }
    },
    getApplicationOAList(query) {
      if (query !== '') {
        this.loading = true
        this.axios({
          method: 'get',
          url: '/basic/user/searchOAUser',
          params: {
            key: query
          }
        }).then(res => {
          if (res.code === 200) {
            this.OAList = res.data.map(item => {
              return {
                ...item,
                showName: item.empno + '----' + item.username
              }
            })
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.OAList = []
      }
    },
    backClick({id}) {
      this.axios({
        method: 'post',
        url: '/dms/dmsBackupScrapApply/revocation',
        data: {
          id
        }
      }).then(res => {
        if (res.code == 200) {
          this.searchList()
        }
      })
    },
    changeCompany(val) {
      // let companyId;
      if (val) {
        // this.searchParams.companyName = this.tagList.find(item => item.id == val).name
        this.getwarehouseList(val)
      } else {
        this.searchParams.warehouseId = ''
        this.warehouseList = []
      }
    },
    getwarehouseList(companyId) {
      this.warehouseList = []
      this.axios({
        method: 'post',
        url: '/dms/dmsBackupConfig/queryBackupsByCompany',
        data: {
          companyId
        }
      }).then(res => {
        if (res.data && res.data.length) {
          this.warehouseList = res.data
        }
      })
    },
    assetsChange() {
      if (this.timerId) {
        clearTimeout(this.timerId)
      }
      this.timerId = setTimeout(() => {
        this.axios({
          method: 'get',
          url: '/dms/dmsCheck/calculationAsset',
          params: {
            original: Number(this.formInfo.assetsOriginal),
            id: this.formInfo.id,
            assetId: this.formInfo.assetId
          }
        }).then(res => {
          this.formInfo.assets = res.data
        })
      }, 600)
    },
    onSelectChange(val) {
      this.selectList = val
    },
    //公司列表
    getCompanyList() {
      this.axios({
        method: 'get',
        url: '/basic/company/getCompanyListByUser',
        params: {}
      }).then(res => {
        
        if (res.code === 200) {
          let arr = res.data.map(item => {
            return {
              ...item,
              id: item.id.toString()
            }
          })
          this.tagList = [...this.tagList, ...arr]
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    handleRangeChange(val) {
      this.searchParams.startTime = val[0]
      this.searchParams.endTime = val[1]
    },
    //批量导出
    handleOutDel() {
      let params = {
        // pageNum: this.pageNum,
        // pageSize: this.pageSize,
        ...this.searchParams
      }
      if (this.selectList && this.selectList.length) {
        params.ids = this.selectList.map(val => val.id)
      }
      const filName = '报废审批'
      this.axios({
        method: 'post',
        url: '/dms/backup/scrapApply/approvalExport',
        responseType: 'blob',
        data: params
      }).then(res => {
        fileDownload(res, filName + '.xlsx')
      })
    },
    //刷新
    handleFresh() {
      this.searchList();
    },
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {
      console.log(this.searchParams);
      let data = {
        pageNo: this.pageNum,
        pageSize: this.pageSize,
        ifFinish: this.ifFinish,
        ...this.searchParams
      }
      this.axios({
        method: 'post',
        url: '/dms/backup/scrapApply/approvalList',
        data
      }).then(res => {
        if (res.code === 200) {
          this.dataArr = res.data.list
          this.total = res.data.total
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.equipmentDataManagement {
  .ivu-tabs.ivu-tabs-card {
    .ivu-tabs-tab {
      width: 120px !important;
      text-align: center;
    }

    /deep/ .ivu-tabs-tab.ivu-tabs-tab-active {
      color: #ffffff;
      background-color: #2d8cf0;
    }
  }
}

.picking {

  .formList {
    padding: 30px;

    .btn {
      margin-top: 20px;
      text-align: center;
      width: 100%;
      height: 40px;
    }

    .inputBorder {
      border: 1px solid #dcdee2;
      border-radius: 4px;

    }
  }
}
</style>

